package com.mijie.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class FileUploadUtil {

	public static String upload(MultipartFile file, String basePath) throws IOException {  
        return upload(file,basePath,UUID.randomUUID().toString());
	}  
	
	public static String upload(MultipartFile file, String basePath,String saveWithName) throws IOException {  
		if(saveWithName==null || saveWithName.trim().isEmpty()) return null;
		String extName = getExtName(saveWithName);
		if(extName.isEmpty()){
			extName = getExtName(file);
			saveWithName += extName;
		}
		if(checkExtName(extName)){
	        if(!basePath.endsWith(File.separator)) basePath += File.separator;
	        FileCopyUtils.copy(file.getBytes(),new File(basePath+saveWithName));
		}
        return saveWithName;
	}  
	
	public static String upload(InputStream is,String extName,String basePath) throws Exception{
		extName = trimExtName(extName);
		String saveName = null;
		
		if(checkExtName(extName)){
			saveName = UUID.randomUUID().toString()+extName;
	        if(!basePath.endsWith(File.separator)) basePath += File.separator;
	        
	        BufferedInputStream bis = null;
	        FileOutputStream fos = null;
	        BufferedOutputStream bos = null;
			try{
				bis = new BufferedInputStream(is);
				fos = new FileOutputStream(basePath+saveName);
				bos = new BufferedOutputStream(fos);
				byte[] buff = new byte[20480];
				int len = -1;
				while((len = bis.read(buff))>0){
					bos.write(buff,0,len);
				}
				bos.flush();
			}catch(Exception e){
				throw e;
			}finally{
				if(bos!=null) bos.close();
				if(fos!=null) fos.close();
				if(bis!=null) bis.close();
				if(is!=null) is.close();
			}
		}
        return saveName;
	}
	
	
	public static String upload(byte[] bytes, String extName,String basePath) throws IOException {
		extName = trimExtName(extName);
		String saveName = null;
		if(checkExtName(extName)){
			saveName = UUID.randomUUID().toString()+extName;
	        if(!basePath.endsWith(File.separator)) basePath += File.separator;
	        FileCopyUtils.copy(bytes,new File(basePath+saveName));
		}
        return saveName;
	}  
	
	private static String trimExtName(String extName){
		if(extName==null || extName.trim().isEmpty()) extName = ".jpg";
		if(!extName.startsWith("."))
			extName = "."+extName.trim();
		return extName;
	}
	
	
	public static String uploadAndNoChangeName(MultipartFile file, String basePath) throws IOException {  
        String extName = getExtName(file); 
        String saveName = null;
        if(checkExtName(extName)){
	        if(!basePath.endsWith(File.separator)) basePath += File.separator;
	        FileCopyUtils.copy(file.getBytes(),new File(basePath+file.getOriginalFilename()));
	        saveName = file.getOriginalFilename();
		}
        return saveName;
	}  
	
	public static boolean validate(MultipartFile file,int maxByte,String ... suffixs) {  
	    if(file.getSize()<0 || file.getSize() > maxByte) return false;  
	    String filename = file.getOriginalFilename();  
	    String extName = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();  
	    for(String suffix : suffixs){
	    	if(extName.equals(suffix)) return true;
	    }
	    return false; 
	}  
	
	public static boolean validate(MultipartFile file,String ... suffixs) {  
	    String filename = file.getOriginalFilename();  
	    String extName = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();  
	    for(String suffix : suffixs){
	    	if(extName.equals(suffix)) return true;
	    }
	    return false; 
	}  
	
	public static Set<MultipartFile> getFileSet(MultipartHttpServletRequest multipartRequest) {  
	    Set<MultipartFile> fileset = new LinkedHashSet<MultipartFile>();  
	    for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) {  
	        String key = it.next();  
	        MultipartFile file = multipartRequest.getFile(key);  
	        if (file.getOriginalFilename().length() > 0) {  
	            fileset.add(file);  
	        }  
	    }  
	    return fileset;  
	}  
	
	public static String getExtName(MultipartFile file){
        return getExtName(file.getOriginalFilename());
	}
	
	public static String getExtName(String url){
		if(url.indexOf(".")==-1) return "";
		return url.substring(url.lastIndexOf(".")).toLowerCase();
	}
	
	private static Set<String> illegalExtName = new HashSet<String>();
	static{
		illegalExtName.add(".sh");
		illegalExtName.add(".js");
		illegalExtName.add(".jsp");
		illegalExtName.add(".java");
		illegalExtName.add(".class");
		illegalExtName.add(".html");
	}
	private static boolean checkExtName(String extName){
		return !illegalExtName.contains(extName);
	}
}
